﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleUnitity.Cache
{
    [Serializable]
    public class MemoryCache : ICache
    {
        private System.Runtime.Caching.MemoryCache cache
        {
            get { return System.Runtime.Caching.MemoryCache.Default; }
        }
        private readonly TimeSpan offset;

        public MemoryCache()
        {
            this.offset = new TimeSpan(0, 30, 0);
        }

        public MemoryCache(TimeSpan abandonTimeSapn)
        {
            this.offset = abandonTimeSapn;
        }

        public void Clear()
        {
            cache.Dispose();
        }

        public void Set(string key, object value)
        {
            cache.Set(key, value, new DateTimeOffset(DateTime.Now, offset));
        }

        public object Get(string key, object defaultValue = null)
        {
            return cache.Contains(key) ? cache.Get(key) : defaultValue;
        }

        public void Remove(string key)
        {
            if (cache.Contains(key))
            {
                cache.Remove(key);
            }
        }

        public bool Exists(string key)
        {
            return cache.Contains(key);
        }

        public ICollection<string> Keys
        {
            get { return cache.GetValues(null).Keys; }
        }
    }
}
